package com.ggstream;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.ggstream.scanner.LinkGetter;

public class Application {

	private static Application app = null ; 

	private List<String> sitesWeb = new ArrayList<String>() ;
	
	private Application() {
	}
	
	public static Application get() {
		if (app==null) {
			app = new Application() ;
		}
		return app ;
	}

	public void nouveauProjet() {
		sitesWeb.clear() ;
	} 
	
	public static void createRecurively(String currentDir, String website) throws IOException {
		System.out.println("create recursively "+website) ;

		// split URL ans get the lateste part of this URL
		String[] URLSplitted = website.split("/") ;
		String Foldername = URLSplitted[URLSplitted.length-1] ;
		
		// the possibility to write into the m3u file
		BufferedWriter writer = null ;
		File dir = new File(currentDir, java.net.URLDecoder.decode( Foldername, "UTF-8")) ;
		boolean succes = dir.mkdir() ;
		if(!succes){
			System.out.println("impossible to create the root folder "+dir.getAbsolutePath()) ;
			return ;
		}
		
		// get the mp3 links on the current URL
		LinkGetter lg = new LinkGetter(website) ;
		lg.regerateLinks() ;
		List<String> ls = lg.getLinks() ;
		List<String> labs = lg.getLabels() ;
		if (ls.size()>0) {
			// into this directory, create a .m3u file
			File fileRoot = new File(dir,  java.net.URLDecoder.decode( dir.getName()+".m3u", "UTF-8")) ;
			try {
				succes = fileRoot.createNewFile() ;
			} catch (IOException e) {
				System.out.println("impossible to create the root m3u file "+fileRoot.getAbsolutePath()) ;
				e.printStackTrace();
				return ;
			}
			try {
				writer = new BufferedWriter(new FileWriter(fileRoot)) ;
			} catch (IOException e) {
				System.out.println("impossible to write into the root m3u file "+fileRoot.getAbsolutePath()) ;
				e.printStackTrace();
				return ;
			}
			// write the introduction of the m3u file
			writer.write("#EXTM3U mp3 from - "+ website + " (a .m3u file)\n") ;
			for (int j = 0; j < ls.size(); j++) {
				writer.write("#EXTINF:-1, "+labs.get(j)+"\n") ;
				writer.write(ls.get(j)+"\n") ;
			}
			writer.flush() ;
			writer.close() ;
		}
		List<String> linksSubWebsite = lg.getURLlinked() ;
		for (int j = 0; j < linksSubWebsite.size(); j++) {
			createRecurively(dir.getAbsolutePath(), linksSubWebsite.get(j)) ;
		}
	}
	
	public static PageScanResult analyseWebPage(String website) {
		
		PageScanResult page = new PageScanResult() ;
		
		// get the mp3 links on the current URL
		LinkGetter lg = new LinkGetter(website) ;
		lg.regerateLinks() ;
		page.setLs(lg.getLinks()) ;
		page.setLabs(lg.getLabels()) ;
		page.setLinksSubWebsite(lg.getURLlinked()) ;
		return page ;
	}
	
}
